package com.wanban.downloader.db.room

import android.text.TextUtils
import androidx.room.TypeConverter

class MapConverters {

    @TypeConverter
    fun stringToList(value: String?): HashMap<String, String>? {
        return if (value == null || TextUtils.isEmpty(value)) {
            null
        } else {
            val hashMap = HashMap<String, String>()
            if (!value.contains(",")) return hashMap
            for (mapArrayStr in value.split(",")) {
                if (!mapArrayStr.contains(":")) continue
                val mapArray = mapArrayStr.split(":")
                if (mapArray.size >= 2) {
                    hashMap[mapArray[0]] = mapArray[1]
                } else {
                    hashMap[mapArray[0]] = ""
                }
            }
            return hashMap
        }

    }

    @TypeConverter
    fun mapToString(data: HashMap<String, String>?): String? {
        if (data == null) return null
        val mapStr = StringBuilder()
        val size = data.size
        data.keys.forEachIndexed { index, key ->
            val value = data[key]
            mapStr.append(key)
            mapStr.append(":")
            mapStr.append(value)
            if (index < size - 1) {
                mapStr.append(",")
            }
        }
        return mapStr.toString()
    }

}